package com.l024.android_ljl.viewmodel.main;

import android.app.Application;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.hjq.toast.ToastUtils;
import com.l024.android_ljl.constant.PageConstant;
import com.l024.android_ljl.entity.SysSubjectEntity;
import com.l024.android_ljl.repository.AppRepository;
import com.quantstack.llcommonlibrary.base.BaseHttpResult;
import com.quantstack.llcommonlibrary.base.BaseObserver;
import com.quantstack.llcommonlibrary.base.BaseViewModel;
import com.quantstack.llcommonlibrary.utils.LogUtils;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wu_ming_zhi_bei
 * @date 2021/5/8 10:19
 * @Notes 搜索
 */
public class SearchViewModel extends BaseViewModel<SysSubjectEntity> {
    public MutableLiveData<String> key;
    public MutableLiveData<List<SysSubjectEntity>> subjects;
    private AppRepository appRepository;
    public SearchViewModel(@NonNull @NotNull Application application) {
        super(application);
        appRepository = new AppRepository();
    }

    public MutableLiveData<String> getKey() {
        if(key==null){
            key = new MutableLiveData<>();
            key.setValue("");
        }
        return key;
    }

    public void setKey(String key) {
       getKey().setValue(key);
    }

    public MutableLiveData<List<SysSubjectEntity>> getSubjects() {
        if(subjects==null){
            subjects = new MutableLiveData<>();
            subjects.setValue(new ArrayList<>());
        }
        return subjects;
    }

    public void setSubjects(List<SysSubjectEntity> subjects) {
        getSubjects().setValue(subjects);
    }

    /**
     * 搜索
     */
    public void search(){
        String value = getKey().getValue();
        if(!TextUtils.isEmpty(value)){
            addDisposable(appRepository.searchSubject(value),new BaseObserver<BaseHttpResult<List<SysSubjectEntity>>>(baseView){
                @Override
                public void onSuccess(BaseHttpResult<List<SysSubjectEntity>> o) {
                    if(o!=null){
                        setSubjects(o.getData());
                    }
                    if(onPageDataListener!=null){
                        onPageDataListener.onSuccess(PageConstant.SEARCH_SUBJECT);
                    }
                }

                @Override
                public void onError(String msg) {
                    LogUtils.e("请求错误:"+msg);
                    if(onPageDataListener!=null){
                        onPageDataListener.onError(PageConstant.SEARCH_SUBJECT,msg);
                    }
                }
            });
        }else{
            ToastUtils.show("搜索内容不可为null");
        }
    }
}